<template>
  <div class="box_wrap mod_train_info">
    <div class="box_wrap_title">
      培训信息
    </div>
    <el-form ref="refModTrainInfo" :model="vo" :rules="formRules" size="medium" label-width="140px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位是否团体会员" prop="isOrganizationRegistered">
            <el-radio-group v-if="!isCheck" v-model="vo.isOrganizationRegistered">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
            <span v-else>{{ vo.isOrganizationRegistered ? '是' : '否' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所在单位名称" prop="organizationName">
            <el-input v-if="!isCheck" v-model.trim="vo.organizationName" placeholder="请输入单位名称" type="text" />
            <span v-else>{{ vo.organizationName }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="现任职务" prop="presentPost">
            <el-input v-if="!isCheck" v-model.trim="vo.presentPost" placeholder="请输入现任职务" type="text" />
            <span v-else>{{ vo.presentPost }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="邮寄地址">
            <template v-if="!isCheck">
              <el-select v-model="vo.provinceCode" class="gl_mr_15" placeholder="请选择所在省" filterable @change="onChangeProvinces">
                <el-option v-for="item in provinces" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
              <el-select v-model="vo.cityCode" class="gl_mr_15" placeholder="请选择所在市" filterable @change="onChangeCities">
                <el-option v-for="item in cities" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
              <el-select v-model="vo.countyCode" class="gl_mr_15" placeholder="请选择所在县" filterable>
                <el-option v-for="item in counties" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </template>
            <span v-else>{{ registerTrainInfo.provinceName }} {{ registerTrainInfo.cityName }} {{ registerTrainInfo.countyName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item v-if="!isCheck" label="">
            <el-input v-model.trim="vo.mailingAddress" type="textarea" :autosize="{ minRows: 3, maxRows: 6}" maxlength="200" show-word-limit />
          </el-form-item>
          <el-form-item v-else label="详细地址">
            <span>{{ vo.mailingAddress }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 自定义字段 -->
      <div v-show="vo.customFields.length" class="box_wrap_title">
        {{ customSettingTitle }}
      </div>
      <template v-for="(item, index) in vo.customFields">

        <el-row v-if="item.fieldTypeCode === 'Text'" :key="index">
          <el-col :span="24">
            <el-form-item :label="item.name">
              <span slot="label"><span class="item_label_star">* </span>{{ item.name }}</span>
              <el-input v-if="!isCheck" v-model.trim="item.value" type="textarea" :autosize="{ minRows: 3, maxRows: 6}" maxlength="200" show-word-limit />
              <span v-else>{{ item.value }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="item.fieldTypeCode === 'Image'" :key="index">
          <el-col :span="24">
            <div class="gl_clear">
              <div class="gl_fl">
                <el-form-item :label="item.name">
                  <span slot="label"><span class="item_label_star">* </span>{{ item.name }}</span>
                  <div style="min-width: 300px" class="gl_clear">
                    <div class="upload_wrap gl_fl">
                      <upload-file
                        v-if="!isCheck"
                        ref="uploadFile"
                        class="imgt_upload"
                        :file-name="'照片'"
                        :max-size="5120"
                        :action="action"
                        :show-file-list="false"
                        :limit="1"
                        file-type="image"
                        format-file=".jpg,.jpeg,.png"
                        :default-file-url="getStaticUrl(item.value)"
                        @uploadSuccess="photoSavePositive($event, item)"
                      />
                      <img v-if="isCheck" class="show_img" :src="getStaticUrl(item.value)">
                      <!-- <div class="imgDelWrap" @click="delImg(item)">
                        <i class="imgDelete el-icon-delete" />
                      </div> -->
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row v-if="item.fieldTypeCode === 'Attachment'" :key="index">
          <el-col :span="24">
            <el-form-item :label="item.name">
              <span slot="label"><span class="item_label_star">* </span>{{ item.name }}</span>
              <el-input v-show="false" v-model.trim="item.value" />
              <upload-file
                v-if="!isCheck"
                ref="entryNoticeUpload"
                :action="docAction"
                file-type="file"
                format-file=".pdf,.doc,.docx"
                :default-file-url="getStaticUrl(item.value)"
                @uploadSuccess="entryNoticeUploadSuccess($event, item)"
              />
              <a
                v-else
                class="download_file color_link"
                target="_blank"
                :href="getStaticUrl(item.value)"
              >附件下载</a>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

    </el-form>
  </div>
</template>

<script>
import uploadFile from './uploadFileDialog';

import {
  SiSTKWTrainCreateTrainningRegisterInput // 创建或更新培训人员特有信息
} from '@/lib/form/train/swaggerForm.js';

import {
  api_GET_Provinces, // 获取省列表(不包括子级)
  api_GET_CitiesProvinceCode, // 根据省的code查询市列表
  api_GET_CountiesCityCode // 根据市的code查询县列表
} from '@/extend/api/trainswaggerApi/district.js';

import { CopyData } from '@/lib';

export default {
  components: {
    uploadFile
  },
  props: {
    registerTrainInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    customSettingTitle: {
      type: String,
      default: ''
    },
    isCheck: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      docAction: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/document`,
      vo: new SiSTKWTrainCreateTrainningRegisterInput(),
      provinces: [], // 省字典
      cities: [], // 市字典
      counties: [], // 县字典
      formRules: {
        isOrganizationRegistered: [
          { required: true, message: '请选择是否团体会员', trigger: 'change' }
        ],
        organizationName: [
          { required: true, message: '请输入单位名称', trigger: 'blur' }
        ],
        presentPost: [
          { required: true, message: '请输入现任职务', trigger: 'blur' }
        ]
      }
    };
  },
  watch: {
    registerTrainInfo: {
      immediate: true,
      deep: true,
      handler (val) {
        if (val.id) {
          // 起始点
          CopyData(this.registerTrainInfo, this.vo);
          this.init();
        } else {
          this.clearInsideUserData();
        }
      }
    }
  },
  methods: {
    // 初始化，非起始点
    init () {
      this.getProvincesAPI();
      if (this.vo.cityCode) {
        this.getCitiesAPI(this.vo.provinceCode);
      }
      if (this.vo.countyCode) {
        this.getCountiesAPI(this.vo.cityCode);
      }
    },
    // 外部获取组件数据的方法
    getInsideUserData () {
      return new Promise((reslove, reject) => {
        this.$refs.refModTrainInfo.validate((valid) => {
          if (valid) {
            reslove(this.vo);
          } else {
            reject(null);
          }
        });
      });
    },
    // 清空数据及验证
    clearInsideUserData () {
      this.vo = new SiSTKWTrainCreateTrainningRegisterInput();
      if (this.$refs.refModTrainInfo) {
        this.$refs.refModTrainInfo.resetFields();
      } else {
        this.$nextTick(() => {
          this.$refs.refModTrainInfo.resetFields();
        });
      }
    },
    // 切换省下拉菜单时
    onChangeProvinces (val) {
      this.cities = [];
      this.counties = [];
      this.vo.cityCode = '';
      this.vo.countyCode = '';
      this.getCitiesAPI(val);
    },
    // 切换市下拉菜单时
    onChangeCities (val) {
      this.counties = [];
      this.vo.countyCode = '';
      if (val !== 'isNull') {
        this.getCountiesAPI(val);
      }
    },
    // 获取省API
    getProvincesAPI () {
      api_GET_Provinces()
        .then(res => {
          this.provinces = res;
        })
        .catch(
          error => {
            this.$message({
              message: `字典获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取市API
    getCitiesAPI (code) {
      api_GET_CitiesProvinceCode(code)
        .then(res => {
          this.cities = res;
        })
        .catch(
          error => {
            this.$message({
              message: `字典获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取县API
    getCountiesAPI (code) {
      api_GET_CountiesCityCode(code)
        .then(res => {
          this.counties = res;
        })
        .catch(
          error => {
            this.$message({
              message: `字典获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取静态文件
    getStaticUrl (relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 上传成功
    photoSavePositive (fileUrl, item) {
      this.$set(item, 'value', fileUrl.tempUrl);
    },
    // 删除图片
    delImg (item) {
      this.$set(item, 'value', '');
    },
    // 文件上传
    entryNoticeUploadSuccess(fileUrl, item) {
      this.$set(item, 'value', fileUrl.tempUrl);
    }
  }
};
</script>

<style lang="scss" scoped>
  .imgt_upload {
    width: 240px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
  }
  .imgt_upload.no_pointer {
    cursor: default;
  }
  .imgt_upload:hover {
    border-color: #409EFF;
  }

  .upload_wrap  {
    position:relative;
    overflow:hidden;
  }
  .imgDelWrap {
    position: absolute;
    top: -29px;
    right: -29px;
    width: 60px;
    height: 60px;
    cursor: pointer;
    transform: rotate(45deg);
    // background-color: rgba(255, 255, 255, 0.8);
  }
  .imgDelete {
    font-size: 18px;
    position: absolute;
    top: 37px;
    left: 21px;
    transform: rotate(-45deg);
    color: rgba(255, 0, 0, 0.8);
  }

  .addImgBtn {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
  }
  .item_label_star {
    color: #ff4949;
  }
  .show_img {
    width: 240px;
    height: 150px;
    border-radius: 4px;
    vertical-align: middle;
  }
  .color_link {
    color: #409EFF;
  }
</style>
